import React, { useState } from 'react';
import moment from 'moment';
import { Card, Table, Tag, Button, Space, Form, Input, Select, DatePicker, Row, Col } from 'antd';
import { SearchOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { Moment } from 'moment';
import './styles.css';

const { RangePicker } = DatePicker;

interface RiskRecord {
  id: string;
  timestamp: string;
  riskLevel: 'high' | 'medium' | 'low';
  riskType: 'transaction_anomaly' | 'compliance_violation' | 'data_quality';
  riskScore: number;
  modelName: string;
  triggerRules: string[];
  transactionId: string;
  entityId: string;
  entityType: 'user' | 'organization' | 'provider';
  entityName: string;
  eventType: string;
  eventAmount: number | null;
  description: string;
  status: 'pending' | 'processing' | 'resolved';
  assignee: string;
  priority: 'high' | 'medium' | 'low';
  processingTime: string | null;
  processingResult: string | null;
  processingNotes: string | null;
  createdAt: string;
  updatedAt: string;
}

// 模拟风险记录数据
const mockRiskRecords: RiskRecord[] = [
  {
    id: 'RISK202403180001',
    timestamp: '2024-03-18 10:15:23',
    riskLevel: 'high',
    riskType: 'transaction_anomaly',
    riskScore: 85,
    modelName: 'TransactionRiskModel_v1',
    triggerRules: ['large_amount', 'unusual_time', 'frequent_trading'],
    transactionId: 'TX2024031801',
    entityId: 'USER2024001',
    entityType: 'user',
    entityName: '张三',
    eventType: 'data_exchange',
    eventAmount: 50000,
    description: '大额交易+异常时间+频繁���易',
    status: 'pending',
    assignee: '李四',
    priority: 'high',
    processingTime: null,
    processingResult: null,
    processingNotes: null,
    createdAt: '2024-03-18 10:15:23',
    updatedAt: '2024-03-18 10:15:23',
  },
  {
    id: 'RISK202403180002',
    timestamp: '2024-03-18 11:30:45',
    riskLevel: 'medium',
    riskType: 'compliance_violation',
    riskScore: 65,
    modelName: 'ComplianceModel_v2',
    triggerRules: ['data_sensitivity', 'unauthorized_access'],
    transactionId: 'TX2024031802',
    entityId: 'ORG2024001',
    entityType: 'organization',
    entityName: '某科技公司',
    eventType: 'data_access',
    eventAmount: null,
    description: '敏感数据访问+权限异常',
    status: 'processing',
    assignee: '王五',
    priority: 'medium',
    processingTime: '2024-03-18 11:45:23',
    processingResult: null,
    processingNotes: '正在核实数据访问权限',
    createdAt: '2024-03-18 11:30:45',
    updatedAt: '2024-03-18 11:45:23',
  },
  {
    id: 'RISK202403180003',
    timestamp: '2024-03-18 14:20:12',
    riskLevel: 'low',
    riskType: 'data_quality',
    riskScore: 35,
    modelName: 'DataQualityModel_v1',
    triggerRules: ['incomplete_data'],
    transactionId: 'TX2024031803',
    entityId: 'PRV2024001',
    entityType: 'provider',
    entityName: '数据提供方A',
    eventType: 'data_upload',
    eventAmount: null,
    description: '数据完整性异常',
    status: 'resolved',
    assignee: '赵六',
    priority: 'low',
    processingTime: '2024-03-18 14:40:12',
    processingResult: 'confirmed',
    processingNotes: '已完成数据修复',
    createdAt: '2024-03-18 14:20:12',
    updatedAt: '2024-03-18 14:40:12',
  },
];

interface SearchFormValues {
  riskId?: string;
  riskLevel?: RiskRecord['riskLevel'];
  riskType?: RiskRecord['riskType'];
  status?: RiskRecord['status'];
  entityId?: string;
  assignee?: string;
  timeRange?: [Moment, Moment];
}

const RiskRecordList: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<RiskRecord[]>(mockRiskRecords);

  const columns: ColumnsType<RiskRecord> = [
    {
      title: '风险编号',
      dataIndex: 'id',
      key: 'id',
      width: 180,
    },
    {
      title: '发生时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 180,
    },
    {
      title: '风险等级',
      dataIndex: 'riskLevel',
      key: 'riskLevel',
      width: 100,
      render: (level: RiskRecord['riskLevel']) => {
        const colorMap = {
          high: 'red',
          medium: 'orange',
          low: 'green',
        };
        const textMap = {
          high: '高风险',
          medium: '中风险',
          low: '低风险',
        };
        return (
          <Tag color={colorMap[level]} icon={level === 'high' ? <ExclamationCircleOutlined /> : null}>
            {textMap[level]}
          </Tag>
        );
      },
    },
    {
      title: '风险类型',
      dataIndex: 'riskType',
      key: 'riskType',
      width: 150,
      render: (type: RiskRecord['riskType']) => {
        const typeMap = {
          transaction_anomaly: '交易异常',
          compliance_violation: '合规违规',
          data_quality: '数据质量',
        };
        return typeMap[type];
      },
    },
    {
      title: '风险分数',
      dataIndex: 'riskScore',
      key: 'riskScore',
      width: 100,
      render: (score: number) => (
        <span style={{ color: score >= 80 ? '#ff4d4f' : score >= 60 ? '#faad14' : '#52c41a' }}>
          {score}
        </span>
      ),
    },
    {
      title: '触发规则',
      dataIndex: 'triggerRules',
      key: 'triggerRules',
      width: 200,
      render: (rules: string[]) => (
        <Space size={[0, 4]} wrap>
          {rules.map((rule) => (
            <Tag key={rule}>{rule}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '关联实体',
      dataIndex: 'entityName',
      key: 'entityName',
      width: 150,
      render: (name: string, record: RiskRecord) => (
        <span>
          {name}
          <br />
          <small style={{ color: '#666' }}>{record.entityId}</small>
        </span>
      ),
    },
    {
      title: '事件信息',
      dataIndex: 'eventType',
      key: 'eventType',
      width: 200,
      render: (type: string, record: RiskRecord) => (
        <>
          <div>{type}</div>
          {record.eventAmount && (
            <small style={{ color: '#666' }}>
              金额: ￥{record.eventAmount.toLocaleString()}
            </small>
          )}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: RiskRecord['status']) => {
        const statusMap = {
          pending: { color: 'gold', text: '待处理' },
          processing: { color: 'blue', text: '处理中' },
          resolved: { color: 'green', text: '已解决' },
        };
        return (
          <Tag color={statusMap[status].color}>
            {statusMap[status].text}
          </Tag>
        );
      },
    },
    {
      title: '处理人',
      dataIndex: 'assignee',
      key: 'assignee',
      width: 100,
    },
    {
      title: '处理结果',
      dataIndex: 'processingNotes',
      key: 'processingNotes',
      width: 200,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      fixed: 'right' as const,
      render: (_: unknown, record: RiskRecord) => (
        <Space>
          <Button type="link" size="small">
            详情
          </Button>
          {record.status === 'pending' && (
            <Button type="link" size="small">
              处理
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const handleSearch = (values: SearchFormValues) => {
    console.log('Search values:', values);
    setLoading(true);
    // 模拟API调用
    setTimeout(() => {
      // 模拟搜索逻辑
      const filteredData = mockRiskRecords.filter(record => {
        if (values.riskId && !record.id.includes(values.riskId)) return false;
        if (values.riskLevel && record.riskLevel !== values.riskLevel) return false;
        if (values.riskType && record.riskType !== values.riskType) return false;
        if (values.status && record.status !== values.status) return false;
        if (values.entityId && !record.entityId.includes(values.entityId) && !record.entityName.includes(values.entityId)) return false;
        if (values.assignee && !record.assignee.includes(values.assignee)) return false;
        if (values.timeRange) {
          const recordTime = moment(record.timestamp);
          if (!recordTime.isBetween(values.timeRange[0], values.timeRange[1], null, '[]')) return false;
        }
        return true;
      });
      setData(filteredData);
      setLoading(false);
    }, 500);
  };

  return (
    <div className="risk-record">
      <Card title="风险记录">
        <Form
          form={searchForm}
          onFinish={handleSearch}
          className="search-form"
        >
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item name="riskId" label="风险编号">
                <Input placeholder="请输入风险编号" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="riskLevel" label="风险等级">
                <Select
                  placeholder="请选择风险等级"
                  allowClear
                  options={[
                    { value: 'high', label: '高风险' },
                    { value: 'medium', label: '中风险' },
                    { value: 'low', label: '低风险' },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="riskType" label="风险类型">
                <Select
                  placeholder="请选择风险类型"
                  allowClear
                  options={[
                    { value: 'transaction_anomaly', label: '交易异常' },
                    { value: 'compliance_violation', label: '合规违规' },
                    { value: 'data_quality', label: '数据质量' },
                  ]}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="status" label="处理状态">
                <Select
                  placeholder="请选择处理状态"
                  allowClear
                  options={[
                    { value: 'pending', label: '待处理' },
                    { value: 'processing', label: '处理中' },
                    { value: 'resolved', label: '已解决' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={6}>
              <Form.Item name="entityId" label="关联实体">
                <Input placeholder="请输入实体ID/名称" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="assignee" label="处理人">
                <Input placeholder="请输入处理人" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="timeRange" label="时间范围">
                <RangePicker showTime style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={4} style={{ textAlign: 'right' }}>
              <Form.Item>
                <Space>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button onClick={() => searchForm.resetFields()}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Table<RiskRecord>
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1800 }}
          pagination={{
            total: data.length,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>
    </div>
  );
};

export default RiskRecordList; 